<?php

namespace oa\services;

use Yii;
use oa\models\Role;

class RoleService extends BaseService
{
    public static function save($id = 0)
    {
        if (empty($id)) {
            $model = new Role();
            $model->scenario = Role::SCENARIO_ADD;
        } else {
            $model = self::one($id);
            $model->scenario = Role::SCENARIO_ADD;
        }
        $data = [
            'name'   => Yii::$app->request->post('name'),
            'remark' => Yii::$app->request->post('remark'),
            'status' => Yii::$app->request->post('status', 1),
            'menu_ids' => implode(",", Yii::$app->request->post('menu_ids')),
        ];
        return $model->_save($data, 1);
    }

    public static function getList()
    {
        $query = Role::find();
        $query->where('status<>-1');
        $query->filterWhere(['status' => Yii::$app->request->get('status')]);
        $query->andFilterWhere(['id' => Yii::$app->request->get('id')]);
        $query->andFilterWhere(['like', 'name', Yii::$app->request->get('name')]);
        $query->orderBy(['created_at' => SORT_DESC]);
        $rows = $query->asArray()->all();
        foreach ($rows as $k => $v) {
            $rows[$k]['updated_at'] = date('Y-m-d H:i', $v['created_at']);
        }
        return ['rows' => $rows];
    }

    public static function getAll()
    {
        return Role::find()->select('name')->where('status=1')->orderBy(['created_at' => SORT_DESC])->asArray()->indexBy('id')->column();
    }

    public static function one($map, $toArray = 0)
    {
        $query = Role::find()->where('status>0');
        if (preg_match('/^[1-9]+[\d]*$/', $map)) {
            $query->andWhere('id=:id', [':id' => $map]);
        } elseif (is_array($map)) {
            $query->andWhere($map[0], $map[1]);
        } else {
            $query->andWhere($map);
        }
        if ($toArray == 1) {
            $query->asArray();
        }
        return $query->one();
    }

    public static function remove($id)
    {
        if (Yii::$app->isAjax) {
            $model = self::one(['id=:id AND status<>-1', [':id' => $id]]);
            $model->scenario = Role::SCENARIO_REMOVE;
            return $model->_save();
        }
    }

    public static function disable($id)
    {
        if (Yii::$app->isAjax) {
            $model = self::one(['id=:id AND status=1', [':id' => $id]]);
            $model->scenario = Role::SCENARIO_DISABLE;
            return $model->_save();
        }
    }

    public static function enable($id)
    {
        if (Yii::$app->isAjax) {
            $model = self::one(['id=:id AND status=2', [':id' => $id]]);
            $model->scenario = Role::SCENARIO_ENABLE;
            return $model->_save();
        }
    }
}